package com.web.dao.novel;

import com.web.bean.novel.Novel;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * @autor Chen
 * @create 2021--25-12:45
 * @desc
 */
public class NovelDaoImpl implements NovelDao {
    private Connection connection = null;
    private PreparedStatement pst = null;
    private ResultSet rs = null;

    public NovelDaoImpl(Connection connection) {
        this.connection = connection;
    }

    public NovelDaoImpl() {

    }

    private Novel getNovel(ResultSet rs) throws Exception{
        Novel novel=new Novel();
        novel.setNid(rs.getString(1));
        novel.setCode(rs.getString(2));
        novel.setNsrc(rs.getString(3));
        novel.setNname(rs.getString(4));
        novel.setSynopsis(rs.getString(5));
        novel.setImgsrc(rs.getString(6));
        novel.setNcount(rs.getInt(7));
        novel.setUid(rs.getString(8));
        return novel;
    }

    @Override
    public List<Novel> selectNovels() throws Exception {
        List<Novel> list=new ArrayList<>();
        String sql = "select * from wn_novel";
        pst=connection.prepareStatement(sql);
        rs=pst.executeQuery();
        while (rs.next()){
            Novel novel=getNovel(rs);
            list.add(novel);
        }
        return list;
    }

    @Override
    public Novel selectById(String nid) throws Exception {
        Novel novel=null;
        String sql="select * from wn_novel where nid=?";
        pst=connection.prepareStatement(sql);
        pst.setObject(1,nid);
        rs=pst.executeQuery();
        while (rs.next()){
            novel=getNovel(rs);
        }
        return novel;
    }

    @Override
    public void addNovel(Novel novel) throws Exception {
        String sql="insert into wn_novel values(????????)";
        pst=connection.prepareStatement(sql);
        pst.setString(1,novel.getNid());
        pst.setString(2,novel.getCode());
        pst.setString(3,novel.getNsrc());
        pst.setString(4,novel.getNname());
        pst.setString(5,novel.getSynopsis());
        pst.setString(6,novel.getImgsrc());
        pst.setInt(7,novel.getNcount());
        pst.setString(8,novel.getUid());
        pst.executeUpdate();
    }

    @Override
    public void updateNovel(Novel novel) throws Exception {
        String sql="update wn_novel set nname=?,synopsis=? where nid=?";
        pst=connection.prepareStatement(sql);
        pst.setString(1,novel.getNname());
        pst.setString(2,novel.getSynopsis());
        pst.setString(3,novel.getNid());
        pst.executeUpdate();
    }

    @Override
    public void deleteNovelById(String nid) throws Exception {
        String sql="delete from wn_novel where id=?";
        pst=connection.prepareStatement(sql);
        pst.setObject(1,nid);
        pst.executeUpdate();
    }
}
